<?php
/**
 * Created by PhpStorm.
 * User: yzapple
 * Date: 2018/1/8
 * Time: 上午11:37
 */

namespace app\index\controller;

use app\common\controller\Commoncontroller;
use app\common\library\UserAuth;
use think\Controller;
use think\Db;
use think\Request;

class Basecontroller extends Commoncontroller
{

    /**
     * 返回码,默认为null,当设置了该值后将输出json数据
     * @var int
     */
    protected $code = null;

    /**
     * 返回内容,默认为null,当设置了该值后将输出json数据
     * @var mixed
     */
    protected $data = null;

    /**
     * 返回文本,默认为空
     * @var mixed
     */
    protected $msg = '';

    /**
     *
     * @var UserAuth
     */
    protected $user = null;
    /**
     * 无需登录的方法，默认全部都无需登录
     * @var array
     */
    protected $noNeedLogin = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $url = '';
        $wxConfig = Config('wx');
        $this->appid = $wxConfig['appid'];
        $this->appsecret = $wxConfig['appsecret'];
        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());

        $path = '/' . $modulename . '/' . str_replace('.', '/', $controllername) . '/' . $actionname;
        $this->user = UserAuth::instance();


        if (session('yxuid') == '' || session('openid') =='') {
            //  echo '登录';
            $this->loginWx();
        }else{

            $this->user->setRequestUri($path);

            $this->user->init();
            $option['openid']= session('openid');
            $option['id']= session('yxuid');
            $user = Db::name('user')->where($option)->find();

            if(!$user){
                $this->loginWx();
            }

        }


        $option['openid']= session('openid');
        $option['id']= session('yxuid');
        $user = Db::name('user')->where($option)->find();

        $this->assign("user", $user);


    }

    public function loginWx(){


        $res =  $this->wxCall();

        $openid = $res['openid'];
        //print_r($openid);
        //根据openid 获取用户的信息
        $option['openid'] = $openid;
        //   $option['is_deleted'] = 1;

        $user =Db::name('user')->where($option)->find();

        // print_r($user);
        // print_r($res);
        if ($user){

            session('yxuid', $user['id']);
            session('openid', $openid);


        }else{


            $data = [
                'openid' => $openid,
                'name' => $res['nickname'],
                'avatar' => $res['headimgurl'],
                'sex' => $res['sex'],
            ];

            $userID =  DB::name("user")->strict(false)->insertGetId($data);
            // print_r($userID);
            session('yxuid', $userID);
            session('openid', $openid);


        }


    }




    /**
     *微信登陆函数
     */
    public function wxCall(){


        $request=Request::instance();

      
        // 获取回调地址 http://xxx.com/public/home/Wxlogin/index
        $url = request()->root(true).'/'.request()->path();
        $url = urlencode($url);

        // 公众号的id和secret
        // $this->appid = $config['appid'];
        // $this->appsecret = $config['appsecret'];

        // 获取code码，用于和微信服务器申请token。 注：依据OAuth2.0要求，此处授权登录需要用户端操作
        if(!$request->get("code")){
            //以下信息可安放在用户登录界面上：
            $url= 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';

            header('Location:'.$url);//跳转到第三方登录入口
            exit;
        }


        //查询当前的token 是否已经过期

        // 依据code码去获取openid和access_token，自己的后台服务器直接向微信服务器申请即可
        //   if(strtotime(session('token_time_mw'))+7200 < strtotime(date('Y-m-d H:i:s',time()))){
        //  if ($request->get("code") && !session("token")){
        session("wxcode",$_GET['code']);

        // session('wxcode',$request->get("code"));

        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid.
            "&secret=".$this->appsecret."&code=".$_GET['code']."&grant_type=authorization_code";
        $res = $this->https_request($url);
        $res_token=(json_decode($res, true));

        $_SESSION['token'] = $res_token;

        session('token',$res_token);
        session('token_time_mw',date('Y-m-d H:i:s',time()));

        //    }
        // }


        //   print_r($_SESSION);

        // 依据申请到的access_token和openid，申请Userinfo信息。
        //if (session("token","access_token")){
        //if ($res_token['access_token']){
        if ($_SESSION['token']['access_token']){
            // $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$res_token['access_token']."&openid=".$res_token['openid']."&lang=zh_CN";
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$_SESSION['token']['access_token']."&openid=".$_SESSION['token']['openid']."&lang=zh_CN";
            //   echo $url;
            $res = $this->https_request($url);
            $res = json_decode($res, true);//最终得到的用户信息
            //session('userinfo',$res);
            // print_r($res);
            $_SESSION['userinfo'] = $res;
            // var_dump( $_SESSION['userinfo']);
            // header('Location:'.Url('User/thirdlogin?userfrom=1'));//跳转到第三方登录入口
            //  exit;
            return $res;

        }

        // print_r($_SESSION);



    }


    // cURL函数简单封装
    function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }




    /**
     * @return 获取openid
     */
    public
    function getOpenid()
    {

        $openid = '';
        //  https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx029ced8b97276573&redirect_uri=http://ccczuo.natapp1.cc/yigou/h5index/user/index&response_type=code&scope=snsapi_base&state=1#wechat_redirect
        $request = Request::instance();
        $code = $request->param('code');

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid .
            "&secret=" . $this->appsecret . "&code=" . $code . "&grant_type=authorization_code";
        $res = https_request($url);
        $res = (json_decode($res, true));
        if (isset($res['openid'])) {
            $openid = $res['openid'];
            session('openid', $openid);

            $user = $this->user->where(array('openid' => $openid))->find();
            if ($user) {

                session('yxuid', $user['id']);
            }
        }

    }


    protected function checkLogin()
    {
        //检测是否登录
        if (!$this->user->isLogin()) {

            return $this->redirect(url('login/index'));

        }
    }
}
        